<template>
  <div class="p-3 flex">
    <div class="w-15/20 h-screen flex flex-col">
      <!-- <GrowCard /> -->
      <div class="flex mb-1">
        <div class="w-1/1 mr-1"><DeviceCard :datalist="device" /></div>
        <div class="w-1/1"><DeviceCard :datalist="alerts" /></div>
      </div>
      <div class="flex">
        <div class="w-1/1 mr-1"><InstrumentCard :datalist="meter" /></div>
        <div class="w-1/1"
          ><InstrumentCard
            :datalist="operation"
            @time-value-select="getTimeValue"
            :echartsList="echartsList"
        /></div>
      </div>
      <div class="flex mt-1 flex-1">
        <div class="w-1/1 mr-1 flex-1"><UsageCard :datalist="link" /></div>
        <div class="w-1/1 mr-1 flex-1"><UsageCard :datalist="document" /></div>
        <div class="w-1/1 mr-1 flex-1"><UsageCard :datalist="usage" /></div>
      </div>
    </div>
    <div class="w-5/20 ml-1 h-screen"><StartUsingCard /> </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  // import GrowCard from './components/GrowCard.vue';
  import DeviceCard from './DeviceCard.vue';
  import InstrumentCard from './InstrumentCard.vue';
  import UsageCard from './UsageCard.vue';
  import StartUsingCard from './StartUsingCard.vue';
  import dayjs from 'dayjs';
  // import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket';
  import { useWebSocket } from '@vueuse/core';
  // let ws = useWebsocketStoreWithOut();
  // 在任意Vue组件内
  const wsUrl = 'ws://47.110.73.94:1523/api/ws/plugins/telemetry?token=';
  const token: any = localStorage.getItem('jwt_token');
  let echartsList = ref<any>([]);
  let send1 = ref<any>({
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [
      {
        query: {
          entityFilter: {
            type: 'entityType',
            resolveMultiple: true,
            entityType: 'DEVICE',
          },
        },
        cmdId: 4,
      },
      {
        query: {
          entityFilter: {
            type: 'entityType',
            resolveMultiple: true,
            entityType: 'DEVICE',
          },
          keyFilters: [
            {
              key: {
                type: 'SERVER_ATTRIBUTE',
                key: 'active',
              },
              valueType: 'BOOLEAN',
              predicate: {
                operation: 'EQUAL',
                value: {
                  defaultValue: true,
                  dynamicValue: null,
                },
                type: 'BOOLEAN',
              },
            },
          ],
        },
        cmdId: 5,
      },
      {
        query: {
          entityFilter: {
            type: 'entityType',
            resolveMultiple: true,
            entityType: 'DEVICE',
          },
          keyFilters: [
            {
              key: {
                type: 'SERVER_ATTRIBUTE',
                key: 'active',
              },
              valueType: 'BOOLEAN',
              predicate: {
                operation: 'EQUAL',
                value: {
                  defaultValue: false,
                  dynamicValue: null,
                },
                type: 'BOOLEAN',
              },
            },
          ],
        },
        cmdId: 6,
      },
    ],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [
      {
        query: {
          statusList: ['ACTIVE'],
          searchPropagatedAlarms: false,
        },
        cmdId: 1,
      },
      {
        query: {
          statusList: ['ACTIVE'],
          searchPropagatedAlarms: false,
          assigneeId: {
            entityType: 'USER',
            id: '5b2e7e60-9b1b-11ee-9f1d-2f70aa1d7dac',
          },
        },
        cmdId: 2,
      },
      {
        query: {
          severityList: ['CRITICAL'],
          statusList: ['ACTIVE'],
          searchPropagatedAlarms: false,
        },
        cmdId: 3,
      },
    ],
    alarmCountUnsubscribeCmds: [],
  });
  let send2 = ref<any>({
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        query: {
          entityFilter: {
            type: 'apiUsageState',
            resolveMultiple: true,
          },
          pageLink: {
            pageSize: 1024,
            page: 0,
            sortOrder: {
              key: {
                type: 'ENTITY_FIELD',
                key: 'createdTime',
              },
              direction: 'DESC',
            },
          },
          entityFields: [
            {
              type: 'ENTITY_FIELD',
              key: 'name',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'label',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'additionalInfo',
            },
          ],
          latestValues: [],
        },
        cmdId: 7,
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  });
  let sendParams = ref<any>({
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        cmdId: 7,
        historyCmd: {
          keys: ['activeDevicesCountHourly'],
          startTs: 1707110446513,
          endTs: 1709702446513,
          interval: 1000,
          limit: 25000,
          agg: 'NONE',
        },
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  });

  const { data, send } = useWebSocket(`${wsUrl}${token}`, {
    autoClose: false,
    autoReconnect: false,
    heartbeat: false,
    onMessage: () => {
      let res = JSON.parse(data.value);
      if (res.cmdUpdateType === 'COUNT_DATA') {
        if (res.cmdId === 4) {
          device.value.value[2].num = res.count;
        } else if (res.cmdId === 5) {
          device.value.value[1].num = res.count;
        } else if (res.cmdId === 6) {
          device.value.value[0].num = res.count;
        }
      } else if (res.cmdUpdateType === 'ALARM_COUNT_DATA') {
        if (res.cmdId === 1) {
          alerts.value.value[2].num = res.count;
        } else if (res.cmdId === 2) {
          alerts.value.value[1].num = res.count;
        } else if (res.cmdId === 3) {
          alerts.value.value[0].num = res.count;
        }
      } else if (res.cmdUpdateType === 'ENTITY_DATA' && res.data === null) {
        res.update[0].timeseries.activeDevicesCountHourly.forEach((item) => {
          echartsList.value.push([dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'), item.value]);
        });
      }
    },
  });
  onMounted(() => {
    send(JSON.stringify(send1.value));
    send(JSON.stringify(send2.value));
    send(JSON.stringify(sendParams.value));
  });
  const device = ref<any>({
    name: '设备',
    key: 'device',
    ant: true,
    value: [
      { title: '活动', num: '10' },
      { title: '未活动', num: '20' },
      { title: '总数', num: '30' },
    ],
  });

  const alerts = ref<any>({
    name: '警报',
    key: 'alarm',
    ant: false,
    value: [
      { title: '严重', num: '10' },
      { title: '分配给我', num: '20' },
      { title: '总数', num: '30' },
    ],
  });

  const meter = ref<Object>({
    name: '仪表盘',
    key: 'dashboard',
    ant: true,
    tabsant: [
      { title: '上次查看', id: 1 },
      { title: '本次', id: 2 },
    ],
  });

  const operation = ref<Object>({
    name: '活动',
    ant: false,
    tabsant: [
      { title: '设备', id: 1 },
      { title: '传输信息', id: 2 },
    ],
  });

  const link = ref<Object>({
    name: '快速链接',
    ant: 1,
  });

  const document = ref<Object>({
    name: '文档',
    ant: 2,
  });

  const usage = ref<Object>({
    name: '用法',
    ant: 3,
    tabsant: [
      { title: '实体', id: 1 },
      { title: 'API调用', id: 2 },
    ],
  });
  function getTimeValue(value) {
    sendParams.value.entityDataCmds[0].historyCmd.startTs = value[0].valueOf();
    sendParams.value.entityDataCmds[0].historyCmd.endTs = value[1].valueOf();
    send(JSON.stringify(sendParams.value));
  }
</script>
